package com.dingup.paike.controller.subscription;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dingup.api.base.HttpResContent;
import com.dingup.paike.bean.config.SysConfigData;
import com.dingup.paike.dao.PkLessonInfoMapper;
import com.dingup.paike.dao.PkLessonStudentSignMapper;
import com.dingup.paike.dao.PkSubscriptionMsgMapper;
import com.dingup.paike.dao.PkUserInfoMapper;
import com.dingup.paike.model.pk.PkLessonStudentSign;
import com.dingup.paike.model.pk.PkUserInfo;
import com.dingup.paike.model.subscription.PkSubscriptionMsg;
import com.dingup.paike.service.message.WxMsgService;
import com.dingup.paike.util.SSpringFactory;
import com.suyeer.basic.util.BEncryptUtil;
import com.suyeer.basic.util.BLogUtil;
import org.apache.commons.codec.Charsets;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Date;

import static com.dingup.api.base.BaseUtil.saveErrorMsgAndData;
import static com.dingup.api.base.BaseUtil.saveSuccessMsgAndData;
import static com.dingup.paike.util.ConstUtil.*;

/**
 * @author jun 2018/10/26
 */
@Controller
@RequestMapping("/subscription")
public class SubscriptionController {

    public final SysConfigData VALIDATE_DATA = SSpringFactory.getBean("validateData");
    private final String SUCCESS_JSON_STR = "{\"error_info\": {\"errno\": 1,\"error\": \"程序正常执行\"}}";
    private final String CODE_IN_CLASS = "67371107";

    @Autowired
    private PkSubscriptionMsgMapper pkSubscriptionMsgMapper;

    @Autowired
    private PkLessonStudentSignMapper pkLessonStudentSignMapper;

    @Autowired
    private PkUserInfoMapper pkUserInfoMapper;

    @Autowired
    private PkLessonInfoMapper pkLessonInfoMapper;

    @Autowired
    private WxMsgService wxMsgService;

    @RequestMapping(value = "/notify.p.do", method = RequestMethod.POST)
    public void subscription(HttpServletRequest request,
                             HttpServletResponse response) {
        HttpResContent<JSONObject> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("消息订阅");
        try {
            // do.
            readData(IOUtils.toString(request.getInputStream(), Charsets.UTF_8));
            JSONObject retObj = JSON.parseObject(SUCCESS_JSON_STR);
            // result
            saveSuccessMsgAndData(hrc, retObj);
        } catch (Exception e) {
            saveErrorMsgAndData(hrc, e);
        } finally {
            writeResResult(hrc.getResult(), response);
        }
    }

    /**
     * User: jun
     * Date: 2017/12/25
     * Desc: 读取数据
     */
    private void readData(String eeoNotifyStr) {
        try {
            JSONObject eeoNotifyObj = JSON.parseObject(eeoNotifyStr);
            String sId = eeoNotifyObj.getString("SID");
            String safeKey = eeoNotifyObj.getString("SafeKey");
            String cmd = eeoNotifyObj.getString("Cmd");
            long timeStamp = eeoNotifyObj.getLong("TimeStamp");
            String md5 = BEncryptUtil.MD5(SYS_CONFIG_DATA.getEeoSecret() + timeStamp).toLowerCase();
            if (!((VALIDATE_DATA.getEeoSid().equals(sId) && md5.equals(safeKey)))) {
                BLogUtil.error("机构验证失败:{}, {}, {}, {}", sId, safeKey, timeStamp, eeoNotifyStr);
                return;
            }
            if (eeoNotifyObj.containsKey("StartTime")) {
                eeoNotifyObj.put("StartTime", eeoNotifyObj.getString("StartTime") + "000");
            }
            if (eeoNotifyObj.containsKey("CloseTime")) {
                eeoNotifyObj.put("CloseTime", eeoNotifyObj.getString("CloseTime") + "000");
            }
            PkSubscriptionMsg pkSubscriptionMsg = new PkSubscriptionMsg();
            pkSubscriptionMsg.setEeoCourseId(eeoNotifyObj.getInteger("CourseID"));
            pkSubscriptionMsg.setEeoClassId(eeoNotifyObj.getInteger("ClassID"));
            pkSubscriptionMsg.setCmd(cmd.toUpperCase());
            pkSubscriptionMsg.setUserId(eeoNotifyObj.getString("LoginMobile"));
            pkSubscriptionMsg.setuId(eeoNotifyObj.getString("UID"));
            pkSubscriptionMsg.setMsg(eeoNotifyObj);
            pkSubscriptionMsg.setStartTime(eeoNotifyObj.getDate("StartTime"));
            pkSubscriptionMsg.setCloseTime(eeoNotifyObj.getDate("CloseTime"));
            addStudentSignInfo(pkSubscriptionMsg);
            pkSubscriptionMsgMapper.add(pkSubscriptionMsg);
        } catch (Exception e) {
            e.printStackTrace();
            BLogUtil.error(e.getMessage());
        }
    }

    private void addStudentSignInfo(PkSubscriptionMsg pkSubscriptionMsg) {
        try {
            PkLessonStudentSign pkLessonStudentSign = new PkLessonStudentSign();
            PkUserInfo pkUserInfo = pkUserInfoMapper.getByUserId(pkSubscriptionMsg.getUserId());
            Integer lessonId = pkLessonInfoMapper.getLessonIdByEeoLessonId(pkSubscriptionMsg.getEeoClassId());
            if (pkUserInfo != null && CODE_IN_CLASS.equals(pkSubscriptionMsg.getCmd())) {
                pkLessonStudentSign.setIfSign(true);
                pkLessonStudentSign.setPkLessonId(lessonId);
                pkLessonStudentSign.setSignTime(new Date());
                pkLessonStudentSign.setUserId(pkUserInfo.getUserId());
                pkLessonStudentSign.setUserName(pkUserInfo.getUserName());
                pkLessonStudentSign.setCreateTime(new Date());
                pkLessonStudentSignMapper.insert(pkLessonStudentSign);
                wxMsgService.sendParentWxMsgForStudentSign(pkLessonStudentSign);
            }
        } catch (Exception e) {
            BLogUtil.error("保存EEO课节签到信息失败.", e);
        }
    }

    private void writeResResult(JSONObject object, HttpServletResponse response) {
        try {
            if (response == null) {
                throw new IllegalArgumentException("parameter error.");
            }
            response.setContentType(CONTENT_TYPE_JSON);
            response.setCharacterEncoding(DEFAULT_ENCODE);
            PrintWriter pw = response.getWriter();
            pw.write(object.toJSONString());
            pw.close();
            pw.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
